package com.zjlanyun.erp.interior.production;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.alibaba.fastjson.JSON;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;

public class Split extends BaseRFIDActivity {

    @Bind(R.id.tv_epc) TextView tv_epc;
    @Bind(R.id.tv_FGongxuName) TextView tv_FGongxuName;
    @Bind(R.id.tv_FName) TextView tv_FName;
    @Bind(R.id.tv_FNumber) TextView tv_FNumber;
    @Bind(R.id.tv_FQty) TextView tv_FQty;
    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_status) TextView tv_status;
    @Bind(R.id.tv_epc_sub) TextView tv_epc_sub;
    @Bind(R.id.tv_FDevName) TextView tv_FDevName;
    @Bind(R.id.tv_FBatchNO) TextView tv_FBatchNO;
    @Bind(R.id.et_FQty_sub) EditText et_FQty_sub;
    @Bind(R.id.ll_submit) LinearLayout ll_submit;
    @Bind(R.id.et_FQty) EditText et_FQty;
    @Bind(R.id.et_FBatchNO_sub) EditText et_FBatchNO_sub;

    private boolean scaning = false;
    private String apiUrl = "";
    private String epc = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.split);
        initBaseView();
        initView();
    }

    private void initView() {
        apiUrl = WebApi.production();
        Bundle bundle = getIntent().getExtras();
        title.setText(bundle.getString("title"));
        ll_submit.setVisibility(View.VISIBLE);

        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tv_epc.getText().toString().equals("")) {
                    new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                finish();
                            }
                        }
                    }).show();
                } else {
                    finish();
                }
            }
        });
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        tv_status.setText("盘询开始");
        scanNumber = 1;
        scaning = true;
        super.startScan();
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            if (epc.equals("")) {
                epc = m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", "");
                getSplitInfo();
            } else if (!m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", "").equals(epc)){
                tv_epc_sub.setText(m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", ""));
            }
        }
    }

    /**
     * 获取母卷信息
     */
    private void getSplitInfo() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", epc);
        param.put("FGongXuNO", "104");
        param.put("FActionFlag", "chaijuan");
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getSplitInfo", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                tv_FName.setText(data.optString("FName"));
                tv_FQty.setText(String.valueOf(data.optDouble("FQty")));
                tv_FDevName.setText(data.optString("FDevName"));
                tv_FBatchNO.setText(data.optString("FBatchNO"));
                tv_FNumber.setText(data.optString("FNumber"));
                tv_FGongxuName.setText(data.optString("FGongxuName"));
                tv_epc.setText(epc);
            }

            @Override
            public void onError(int what, Response<JSONObject> response) {
                epc = "";
            }
        });
    }

    @OnClick(R.id.ll_submit)
    public void submit(){
        if (tv_epc.getText().toString().equals("")){
            Toastor.getInstance().showShortToast("请扫母卷的卡");
            return;
        } else if (tv_epc_sub.getText().toString().equals("")){
            Toastor.getInstance().showShortToast("请扫子卷的卡");
            return;
        } else if (et_FQty.getText().toString().equals("")){
            Toastor.getInstance().showShortToast("请输入母卷数量");
            return;
        } else if (et_FQty_sub.getText().toString().equals("")){
            Toastor.getInstance().showShortToast("请输入子卷数量");
            return;
        }

        //有两种情况，一种是成品拆两卷，轴号都要，另一种，退原料，可以不输入轴号；给个提示，或者选择，成品，必输，选择材料不输入
        if (et_FBatchNO_sub.getText().toString().equals("")) {
            new AlertView("提示", "子卷轴号未输入，确定提交吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    if (position == 0) {
                        send();
                    }
                }
            }).show();
        } else {
            send();
        }


    }

    private void send(){
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", tv_epc.getText().toString());
        param.put("epc_sub", tv_epc_sub.getText().toString());
        param.put("FQty", et_FQty.getText().toString());
        param.put("FQty_sub", et_FQty_sub.getText().toString());
        param.put("FBatchNO_sub", et_FBatchNO_sub.getText().toString().replace(" ", "").toUpperCase());
        param.put("FGongXuNO", "104");
        param.put("FActionFlag", "chaijuan");
        final HttpRequest client = new HttpRequest(mContext, apiUrl, "postSplit", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                Toastor.getInstance().showShortToast(R.string.submit_success);
                clean();
            }
        });
    }

    @OnClick(R.id.btn_reset)
    public void reset(){
        clean();
    }

    /**
     * 重置
     */
    private void clean(){
        epc = "";
        tv_epc.setText("");
        tv_FName.setText("");
        tv_FNumber.setText("");
        tv_FQty.setText("");
        et_FQty.setText("");
        tv_epc_sub.setText("");
        et_FQty_sub.setText("");
        et_FBatchNO_sub.setText("");
        tv_FDevName.setText("");
        tv_FBatchNO.setText("");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (!tv_epc.getText().toString().equals("")) {
                new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            finish();
                        }
                    }
                }).show();
                return false;
            }
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
